﻿//生成边框刻度
function InitBorderScale() {
    // 定义x和y方向的范围
    const xMin = 0;
    const xMax = 100; // x方向的最大值
    const yMin = 0;
    const yMax = 50; // y方向的最大值

    const rulerHorizontal = document.querySelector(".ruler-horizontal");
    const rulerVertical = document.querySelector(".ruler-vertical");

    // 水平刻度：10个刻度（包括起点和终点）
    const numTicksX = 10; // 总刻度数
    const horizontalWidth = rulerHorizontal.offsetWidth; // 容器宽度
    const stepX = horizontalWidth / (numTicksX - 1); // 刻度间距

    for (let i = 0; i < numTicksX; i++) {
        const tick = document.createElement("div");
        tick.classList.add("tick");
        tick.style.left = `${i * stepX}px`;
        tick.style.top = "10px"; // 刻度线的位置
        rulerHorizontal.appendChild(tick);

        // 计算刻度值
        const value = ((i / (numTicksX - 1)) * (xMax - xMin) + xMin).toFixed(2); // 线性映射
        const label = document.createElement("span");
        label.textContent = value;
        label.style.left = `${i * stepX}px`;
        label.style.top = "25px"; // 标签的位置
        label.style.transform = "translateX(-50%)";
        rulerHorizontal.appendChild(label);
    }

    // 垂直刻度：10个刻度（包括起点和终点）
    const numTicksY = 10; // 总刻度数
    const verticalHeight = rulerVertical.offsetHeight; // 容器高度
    const stepY = verticalHeight / (numTicksY - 1); // 刻度间距

    for (let i = 0; i < numTicksY; i++) {
        const tick = document.createElement("div");
        tick.classList.add("tick");
        tick.style.top = `${i * stepY}px`;
        tick.style.left = "10px"; // 刻度线的位置
        rulerVertical.appendChild(tick);

        // 计算刻度值（修正顺序）
        const value = (yMax - ((i / (numTicksY - 1)) * (yMax - yMin))).toFixed(2); // 从上到下递增
        const label = document.createElement("span");
        label.textContent = value;
        label.style.top = `${i * stepY}px`;
        label.style.left = "25px"; // 标签的位置
        label.style.transform = "translateY(-50%)";
        rulerVertical.appendChild(label);
    }
}

class Region {
    constructor(index, startX, startY, width, height, name, isSelected = false) {
        this.index = index;
        this.startX = startX;
        this.startY = startY;
        this.width = width;
        this.height = height;
        this.name = name;
        this.isSelected = isSelected;
    }
}

let CanvaseId = null; //Canvas id
let regions = []; // 存储所有矩形的数组  
let isDrawing = false; // 是否正在绘制新矩形的标志  
let currentRect = null; // 当前正在绘制的矩形
let selectedRect = null; // 当前选中的矩形
var dotnetHelper;
let isCanDraw = false;//是否可以画

function initCanvas(DotnetHelper, canvaseId, IsCanDraw) {
    CanvaseId = canvaseId;
    var canvas = document.getElementById(canvaseId);
    isCanDraw = IsCanDraw;
    this.dotnetHelper = DotnetHelper;
    canvas.addEventListener('mousedown', canvasmousedown);

    canvas.addEventListener('mousemove', function (e) {
        if (!isCanDraw)
            return;
        if (regions.length > 1)
            return;
        if (!isDrawing) return;

        //dotnetHelper.invokeMethodAsync('MouseMove', e.offsetX, e.offsetY);

        const width = e.offsetX - currentRect.startX;
        const height = e.offsetY - currentRect.startY;
        currentRect.width = parseFloat(width);
        currentRect.height = parseFloat(height);
        drawRegion(); // 更新并绘制当前矩形 
    });

    canvas.addEventListener('mouseup', canvasemouseup);

}
function GetIndex() {
    if (regions.length == 0)
        return 1;
    if (regions.length == 1) {
        var index = regions[0].index;
        if (index == 1)
            return 2;
        return 1;
    }
    return 0;
}

function canvasmousedown(e) {
    if (!isCanDraw)
        return;

    //dotnetHelper.invokeMethodAsync('MouseDown', e.offsetX, e.offsetY);
    isDrawing = true;
    var canvas = document.getElementById(CanvaseId);
    const rect = canvas.getBoundingClientRect();
    const x = e.offsetX; //e.clientX - rect.left;
    const y = e.offsetY; //e.clientY - rect.top;

    regions.forEach(function (item, index) {
        item.isSelected = false;
    });
    selectedRect = null;
    for (let i = regions.length - 1; i >= 0; i--) {
        if (isPointInRect(regions[i], x, y)) {
            regions[i].isSelected = true;
            selectedRect = regions[i];
            break;
        }
    }
    var index = GetIndex();
    currentRect = new Region(index, parseFloat(x), parseFloat(y), 0, 0, "", true);
    drawRegion(); // 绘制初始矩形（只是一个点） 
}

function canvasemouseup(e) {
    isDrawing = false;

    let isRect = false;
    if (currentRect && currentRect.width !== 0 && currentRect.height !== 0) {
        var isExist = regions.filter(function (item) {
            return item.startX === currentRect.startX && item.startY === currentRect.startY && item.width === currentRect.width && item.height === currentRect.height;
        });
        if (isExist.length === 0) {
            regions.push({ ...currentRect }); // 存储完成的矩形  
        }
        isRect = true;
    }

    if (selectedRect) {
        dotnetHelper.invokeMethodAsync('MouseSelect', selectedRect);
    }
    else {
        if (isRect)
            dotnetHelper.invokeMethodAsync('MouseSelect', currentRect);
        else
            dotnetHelper.invokeMethodAsync('MouseSelect', null);
    }
    currentRect = null; // 重置当前矩形 
}

//清空canvas
function clearCanvasRect() {
    isCanDraw = false;
    var canvas = document.getElementById(CanvaseId);
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    regions = [];

    canvas.removeEventListener('mouseup', canvasemouseup);
    canvas.addEventListener('mouseup', canvasemouseup);
}

// 添加一个函数来检测点击的坐标是否在某个矩形内  
function isPointInRect(rect, x, y) {
    var endX = rect.startX + (rect.width);
    var endY = rect.startY + (rect.height);

    let rx = Math.min(rect.startX, endX);
    let ry = Math.min(rect.startY, endY);
    let width = rect.width;
    let height = rect.height;
    return x >= rx && x <= rx + width &&
        y >= ry && y <= ry + height;
}

function drawRegion() {
    var canvas = document.getElementById(CanvaseId);
    var ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布上的内容


    if (currentRect && currentRect.width !== 0 && currentRect.height !== 0) {
        drawRect(currentRect); // 绘制当前矩形  
        regions.forEach(function (item, index) {
            item.isSelected = false;
        });
    }

    // 绘制所有矩形  
    regions.forEach(rect => {
        ctx.beginPath();
        ctx.rect(rect.startX, rect.startY, rect.width, rect.height);
        ctx.lineWidth = 2; // 正常矩形的线宽
        ctx.strokeStyle = rect.isSelected ? 'red' : 'green'
        ctx.stroke();

        //显示文字
        if (rect.index) {
            ctx.font = "16px Arial";
            ctx.fillStyle = "black";
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            var name = "Region " + rect.index.toString();
            ctx.fillText(name, rect.startX + rect.width / 2, rect.startY + rect.height / 2);
        }
    });
}

function drawRect(rect) {
    var canvas = document.getElementById(CanvaseId);
    var ctx = canvas.getContext('2d');
    ctx.beginPath();
    ctx.lineWidth = 2; // 例如，使用更宽的线宽  
    ctx.strokeStyle = 'red'; // 使用红色边框
    ctx.rect(rect.startX, rect.startY, rect.width, rect.height);
    ctx.stroke();

    //显示文字
    if (rect.index) {
        ctx.font = "16px Arial";
        ctx.fillStyle = "black";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        var name = "Region " + rect.index.toString();
        ctx.fillText(name, rect.startX + rect.width / 2, rect.startY + rect.height / 2);
    }
}

//删除矩形
function deleteDraw(index) {
    regions = regions.filter(function (item) {
        return item.index !== index;
    });
    drawRegion(); // 重新绘制
}

//获取所有图形
function GetAllRectangle() {
    return regions;
}

//渲染矩形
function RenderRectangle(rects) {
    regions = [];
    for (let i = rects.length - 1; i >= 0; i--) {
        var rect = rects[i];
        var insert = new Region(rect.startX, rect.startY, rect.width, rect.height, rect.name, false);
        regions.push({ ...insert }); // 存储完成的矩形  
    }
    drawRegion();
}